import ConfirmModal from '@/components/ConfirmModal';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import { queryCompanies } from '../SystemUser/service';
import ConfigChargeRule from './components/ConfigChargeRule';
import FreeTimes from './components/FreeTimes';
// import FreeTimes from './components/FreeTimes';
import RulesDetail from './components/RulesDetail';
import TestChargeRule from './components/TestChargeRule';
import UpdateChargeRule from './components/UpdateChargeRule';
import { queryChargeRules, removeChargeRule } from './service';
import type { ChargeRuleTableItem } from './types.d';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.chargeRule || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifCreate = auths.has(Auths.CREATE);
  const [currRule, setCurrRule] = useState<ChargeRuleTableItem | null>(null);
  const [updateVisible, setUpdateVisible] = useState<boolean>(false);
  const [testVisible, setTestVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<ChargeRuleTableItem>[] = [
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      align: 'center',
      fieldProps: { showSearch: true },
      render: (_, record) => record.ownerInfo?.ownerName || record.ownerId,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
    },
    {
      title: '规则编号',
      dataIndex: '_id',
      hideInForm: true,
      align: 'center',
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '规则名称',
      dataIndex: 'name',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '免费时段',
      dataIndex: 'freeTimes',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => (
        <FreeTimes times={record.commonSmall?.freeTimes || record.freeTimes} size="small" />
      ),
    },
    {
      title: '免费时长(min)',
      dataIndex: 'freeMin',
      hideInForm: true,
      align: 'center',
      hideInSearch: true,
      renderText: (_, record) => record.commonSmall?.freeMin || record.freeMin,
    },
    {
      title: '日最高限额(元)',
      dataIndex: 'dayMax',
      hideInForm: true,
      align: 'center',
      hideInSearch: true,
      renderText: (_, record) => ((record.commonSmall?.dayMax || record.dayMax) / 100).toFixed(2),
    },
    {
      title: '规则描述',
      dataIndex: 'description',
      hideInForm: true,
      hideInSearch: true,
      ellipsis: true,
      render: (_, record) => {
        return (
          <div
            style={{
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              width: 200,
            }}
          >
            {record.description}
          </div>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      valueType: 'option',
      render: (_, record, x, action) => [
        <a
          key={`${record._id}_check`}
          onClick={() => {
            setCurrRule(record);
            setTestVisible(true);
          }}
        >
          校验
        </a>,
        ifModify && (
          <a
            key={`${record._id}_edit`}
            onClick={() => {
              setCurrRule(record);
              setUpdateVisible(true);
            }}
          >
            编辑
          </a>
        ),
        ifDelete && (
          <ConfirmModal
            reload={() => action?.reload()}
            operFunc={async () => await removeChargeRule(record._id)}
            text={`是否确定删除收费规则「${record.name}」`}
          />
        ),
      ],
    },
  ];

  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '收费规则列表',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            {
              path: '/charge-rule',
              breadcrumbName: '收费规则',
            },
          ],
        },
      }}
    >
      <ProTable<ChargeRuleTableItem>
        scroll={{ x: true }}
        columns={columns}
        actionRef={actionRef}
        search={{
          labelWidth: 'auto',
        }}
        style={{ whiteSpace: 'nowrap' }}
        rowKey="_id"
        columnEmptyText="暂无数据"
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryChargeRules(param, sort);
          return res;
        }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        expandable={{
          expandedRowRender: (record) => <RulesDetail chargeRule={record} />,
        }}
        toolBarRender={(action) => [
          ifCreate && <ConfigChargeRule reload={() => action?.reload()} key="ConfigChargeRule" />,
        ]}
      />
      {currRule && updateVisible && (
        <UpdateChargeRule
          currItem={currRule}
          visible={updateVisible}
          setUnvisible={() => {
            setCurrRule(null);
            setUpdateVisible(false);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
        />
      )}
      {currRule && testVisible && (
        <TestChargeRule
          currItem={currRule}
          visible={testVisible}
          setUnvisible={() => {
            setCurrRule(null);
            setTestVisible(false);
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};
